//
//  ShopViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/30.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ShopViewController.h"
#import "ShoppingProductListCell.h"
#import "ShoppingProductDetailViewController.h"
#import "ForSalePaperTableViewCell.h"
#import "UMSocialScreenShoter.h"
#import "UMSocialShakeService.h"
#import "UMSocialControllerService.h"
static NSString *CellWithIdentifier = @"ShoppingProductListCell";
static NSString *cellWithIdentifier = @"ForSalePaperTableViewCell";
@interface ShopViewController ()<DYQBannerScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong,nonatomic) DYQBannerScrollView *bannerScrollView;//广告栏
@property (strong, nonatomic) UISwipeGestureRecognizer * rightGesture;

@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (strong, nonatomic) IBOutlet UIView *navSearchView;
@property (strong, nonatomic) IBOutlet UITextField *searchField;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UIScrollView *backScroView;
@property (strong, nonatomic) IBOutlet UITableView *forSaleTableView;
@property (strong, nonatomic) IBOutlet UIView *forSalePaperView;
@property (strong, nonatomic) IBOutlet UILabel *score;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIView *typeButtonView;
@property (strong, nonatomic) IBOutlet UIButton *priceOrderButton;
@property (strong, nonatomic) IBOutlet UIButton *screenOrderButton;
@property (strong, nonatomic) IBOutlet UICollectionView *listCollectionView;
@property (strong, nonatomic) IBOutlet UIButton *getForSaleButton;
@property (strong, nonatomic) IBOutlet UILabel *forSaleLabel;//优惠劵
@property (strong, nonatomic) IBOutlet UIButton *forSaleButton;
@property (strong, nonatomic) IBOutlet UIImageView *forSaleImage;

@property (strong, nonatomic) IBOutlet UILabel *cutDownPrice;//满减
@property (strong, nonatomic) IBOutlet UIView *cutDownLine;
@property (strong, nonatomic) IBOutlet UIButton *cutDownButton;
@property(nonatomic,assign)NSInteger selectedIndex;
@property(nonatomic,strong)NSMutableArray * goodsArray;
@property(nonatomic,assign)NSInteger count;//按钮点击计数

@property (strong, nonatomic) IBOutlet UIButton *openTypeButton;
@property (strong, nonatomic) IBOutlet UITableView *typeTableView;
@property (nonatomic,strong)NSArray * typesArray;
@property (strong, nonatomic) NSString *storePhone;
@property (strong, nonatomic) NSMutableArray *storeClassifyArrary;
@property (strong, nonatomic) NSString *mgooStoreTypeId;//店铺分类id
@property(strong,nonatomic)NSMutableArray * couponArray;

@property(nonatomic,assign)CGFloat offSet;
@end

@implementation ShopViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([Common getLoginStatus]) {
        [self ifCollected];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    self.navSearchView.layer.masksToBounds = YES;
    self.navSearchView.layer.cornerRadius = 17;
    self.navSearchView.layer.borderWidth = 1;
    self.navSearchView.layer.borderColor = kGetColor(230, 230, 230).CGColor;
    _selectedIndex = 101;
    self.storePhone = @"";
    self.mgooStoreTypeId = @"";
    self.storeClassifyArrary = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];
    _goodsArray = [NSMutableArray array];
    _couponArray = [NSMutableArray array];
    [self initViewLayout];
    [self getAdvertiseBanner];
    [self addRefreshing];
    [self getStoreInfo];
    [self queryMallStoreCategoryInfo];
    [self getStoreForSale];
    [self getStoreSale];
}

- (void)initViewLayout{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.backScroView];
    [self adaptiveViewLayout:self.navSearchView];
    [self adaptiveViewLayout:self.forSalePaperView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.typeButtonView];
    [self.openTypeButton addGestureRecognizer:self.rightGesture];
    self.rightGesture.enabled = NO;
    _backScroView.contentSize = flexibleSize(CGSizeMake(0, 779), NO);
//    _backScroView.scrollEnabled = NO;
    _backScroView.delegate = self;
    
    //广告栏
    self.bannerScrollView = [[DYQBannerScrollView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 140), NO)];
    self.bannerScrollView.backgroundColor = [UIColor clearColor];
    self.bannerScrollView.pageControlPosition = PageControlPositionCenter;
    self.bannerScrollView.noDataPlaceholderImage = [UIImage imageNamed:@"cover_cy"];
    self.bannerScrollView.timeInterval = 3;
    self.bannerScrollView.pageControllerTintColor = [UIColor whiteColor];
    self.bannerScrollView.pageControllerCurrentColor = [UIColor orangeColor];
    
    [self.scroView addSubview:_bannerScrollView];
    [self.scroView insertSubview:_bannerScrollView belowSubview:_score];
    
    CommitStarsView * serviceStars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(7, 125, 57, 10), NO) SmallStars:3.5];
    [_scroView insertSubview:serviceStars belowSubview:_score];
    
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 3*VerticalRatio();
    flowLayout.minimumLineSpacing = 3*VerticalRatio();
    self.listCollectionView.collectionViewLayout = flowLayout;
    self.listCollectionView.userInteractionEnabled=YES;
    [self.listCollectionView registerNib:[UINib nibWithNibName:CellWithIdentifier bundle:nil] forCellWithReuseIdentifier:CellWithIdentifier];
    self.listCollectionView.alwaysBounceVertical = YES;



    _typeTableView.dataSource = self;
    _typeTableView.delegate = self;
    self.typeTableView.separatorStyle = NO;
    
    
    [self.forSaleTableView registerNib:[UINib nibWithNibName:cellWithIdentifier bundle:nil] forCellReuseIdentifier:cellWithIdentifier];

    
}
- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}


#pragma mark  === 选择分类
- (IBAction)morehandel:(id)sender {
    
     _openTypeButton.hidden = NO;
    _openTypeButton.alpha = 0;
    [UIView animateWithDuration:0.5 animations:^{
        _typeTableView.frame = flexibleFrame(CGRectMake(130, 0, 190, 568), NO);
        _openTypeButton.alpha = 1;
    }];
    self.rightSwipeGesture.enabled = NO;
    self.rightGesture.enabled = YES;
}

- (IBAction)closeTypeView:(id)sender {
    [UIView animateWithDuration:0.4 animations:^{
        _typeTableView.frame = flexibleFrame(CGRectMake(320, 0, 190, 568), NO);
        _forSalePaperView.frame = flexibleFrame(CGRectMake(0, 568, 320, 343), YES);
        _openTypeButton.alpha = 0;
    } completion:^(BOOL finished) {
        _openTypeButton.hidden=YES;

    }];
    self.rightSwipeGesture.enabled = YES;
    
    
}

#pragma mark == 领取优惠券
- (IBAction)getForSalePaper:(id)sender {

    [UIView animateWithDuration:0.5 animations:^{
        _forSalePaperView.frame = flexibleFrame(CGRectMake(0, 225, 320, 323), YES);
    }];
    _openTypeButton.hidden = NO;
    _openTypeButton.alpha = 1;
}
#pragma mark === 获取商家分类信息
- (void)getStoreTypes{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_storeId forKey:@"storeId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallStoreCategoryInfo withHttpType:@"POST" withTag:SX_SX_queryMallStoreCategoryInfo];
}


#pragma mark ====查询商家信息
- (void)getStoreInfo{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_storeId forKey:@"storeId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallStoreDetailInfo withHttpType:@"POST" withTag:SX_SX_queryMallStoreDetailInfo];
    
}


#pragma mark ====查询商家是否收藏
- (void)ifCollected{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_storeId forKey:@"storeId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryStoreIsCollect withHttpType:@"POST" withTag:SX_SX_queryStoreIsCollect];

}
#pragma mark ====查询店铺分类列表
- (void)queryMallStoreCategoryInfo{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_storeId forKey:@"storeId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallStoreCategoryInfo withHttpType:@"POST" withTag:SX_queryMallStoreCategoryInfoTag];
    
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.backScroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.backScroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getGoodsList];
        });
    }];
    // 马上进入刷新状态
    [self.backScroView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.goodsArray.count == _totle) {
        [self.listCollectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getGoodsList];
        });
    }
    
}


#pragma mark ====查询店铺内商品列表
- (void)getGoodsList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if (_storeId) {
        [dic setObject:self.storeId forKey:@"mgooPublishStoreId"];
    }
    if (_searchField.text.length>0) {
        [dic setObject:_searchField.text forKey:@"mgooName"];
    }
    [dic setObject:self.mgooStoreTypeId forKey:@"mgooStoreTypeId"];
    if (_selectedIndex == 101) {
//        [dic setObject:@"intelligence" forKey:@"sort"];
        [dic setObject:@"" forKey:@"sort"];
    }else  if (_selectedIndex == 102){
        [dic setObject:@"time" forKey:@"sort"];
    }else if (_selectedIndex == 103){
        if (_count%2==0) {
            [dic setObject:@"price_desc" forKey:@"sort"];
        }else{
            [dic setObject:@"price_asc" forKey:@"sort"];
        }
        
    }else if (_selectedIndex == 104){
        [dic setObject:@"saleno" forKey:@"sort"];
        //        if (_count%2==0) {
        //            [dic setObject:@"DESC" forKey:@"selledCountSort"];
        //        }else{
        //            [dic setObject:@"ASC" forKey:@"selledCountSort"];
        //        }
    }
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_GetGoodsLists withHttpType:@"POST" withTag:SX_GetGoodsList];
    
}

#pragma   mark  类型选择======================================

- (IBAction)choseTheType:(UIButton *)sender {
    
    if (sender.tag == 103){
        _screenOrderButton.selected = NO;
        _priceOrderButton.selected = YES;
    }else if (sender.tag == 104){
        _screenOrderButton.selected = YES;
        _priceOrderButton.selected = NO;
    }
    
    if (sender.tag==_selectedIndex) {
        _count +=1;
        
        if (sender.tag==103) {
            _priceOrderButton.selected = YES;
            _screenOrderButton.selected = NO;
            if (_count%2==0) {//价格升序
                [_priceOrderButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
                
            }else{//价格降序
                [_priceOrderButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
                
            }
            
            [self getGoodsList];
        }else if (sender.tag == 104){
            _screenOrderButton.selected = YES;
            _priceOrderButton.selected = NO;
            if (_count%2==0) {//销量升序
                [_screenOrderButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
            }else{//销量降序
                [_screenOrderButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
            }
            
            [self getGoodsList];
        }
        return;
        
    }
    _count = 0;
    sender.selected = YES;
    UIButton * button = (UIButton *)[self.view viewWithTag:_selectedIndex];
    button.selected = NO;
    _selectedIndex = sender.tag;
    
    if (sender.tag!=103 && sender.tag!=104) {
        _screenOrderButton.selected = NO;
        _priceOrderButton.selected = NO;
    }
    
    [self getGoodsList];
}
#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}



#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.storeId forKey:@"storeId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryStoreBanner withHttpType:@"POST" withTag:SX_SX_queryStoreBanner];
}

#pragma mark  获取店铺促销--=========================================
-(void)getStoreSale{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.storeId forKey:@"storeId"];

    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryStoreOffline withHttpType:@"POST" withTag:SX_SX_queryStoreOffline];
}

#pragma mark  获取店铺优惠--=========================================
-(void)getStoreForSale{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.storeId forKey:@"storeId"];
    if (![Common getLoginStatus]) {
         [dic setObject:@"" forKey:@"userId"];
    }else{
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"userId"];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryDesc withHttpType:@"POST" withTag:SX_SX_queryDesc];
}

#pragma mark  地图--=========================================
- (IBAction)mapHandel:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _mapTitle.selected = YES;
        _phoneButton.selected = NO;
        _phoneTitle.selected = NO;
        _shareButton.selected = NO;
        _shareTitle.selected = NO;
    }else{
        _mapTitle.selected = NO;
    }
    
}

#pragma mark  电话--=========================================
- (IBAction)callHandel:(UIButton *)sender {
   
    sender.selected = !sender.selected;
    if (sender.selected) {
        [Common callPhone:self.storePhone view:self.view];
        
        _phoneTitle.selected = YES;
        _mapTitle.selected = NO;
        _mapButton.selected = NO;
        _shareButton.selected = NO;
        _shareTitle.selected = NO;
   
    }else{
        _phoneTitle.selected = NO;
    }
}

#pragma mark  收藏店铺--=========================================
- (IBAction)collectStoreClick:(UIButton *)sender {
   
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"addGoodsCollectInfo" forKey:@"method"];
        [dic setObject:@"2" forKey:@"collectType"];
        [dic setObject:self.storeId forKey:@"goodsId"];
        [dic setObject:@"1" forKey:@"storeType"];

        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_AddGoodsCollectInfo withHttpType:@"POST" withTag:SX_AddGoodsCollectInfoTag];
        

         sender.selected = !sender.selected;
        if (sender.selected) {
            _collectTitle.selected = YES;
            _phoneButton.selected = NO;
            _phoneTitle.selected = NO;
            _shareButton.selected = NO;
            _shareTitle.selected = NO;
            _mapButton.selected = NO;
            _mapTitle.selected = NO;
        }else{
            _collectTitle.selected = NO;
        }
       
    }
}

#pragma mark  分享--=========================================
- (IBAction)shareHandel:(UIButton *)sender {
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{

        
        sender.selected = !sender.selected;
        if (sender.selected) {
            _shareTitle.selected = YES;
            _phoneButton.selected = NO;
            _phoneTitle.selected = NO;
            _mapButton.selected = NO;
            _mapTitle.selected = NO;
            
            //分享内嵌文字
            NSString *shareText;
            shareText = [NSString stringWithFormat:@"凡人街在线商城"];
            
            UIImage *shareImage = [UIImage imageNamed:@"58"];          //分享内嵌图片
            
            //调用快速分享接口
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:UmengAppkey
                                              shareText:shareText
                                             shareImage:shareImage
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone,nil]
                                               delegate:nil];
        }else{
            _shareTitle.selected = NO;
        }
    }
}




#pragma mark----DYQBannerScrollViewDelegate

-(void)bannerScrollView:(DYQBannerScrollView *)bannerScrollView didSelectItemAtIndex:(NSInteger)index
{
    //    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
    //    WebDetailInfoViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WebDetailInfo"];
    //    page.objectId = _bannerArray[index][@"appAdertUrl"];
    //    page.titleStr = @"详情";
    //    page.meType = @"4";
    //    [self.navigationController  pushViewController:page animated:YES];
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _goodsArray.count;
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(154*VerticalRatio(), 201*VerticalRatio());
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 3*VerticalRatio(), 3*VerticalRatio(), 3*VerticalRatio());
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingProductListCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellWithIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    NSString * image = _goodsArray[indexPath.row][@"appAdertImagUri"];
    if (image.length>0) {
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString: image]];
    }else{
        cell.imageView.image =[UIImage imageNamed:@"cloth1"];
    }
    
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",_goodsArray[indexPath.row][@"mgooPublishPrice"]];
    cell.nameLabel.text = _goodsArray[indexPath.row][@"mgooName"];;
    
    
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShoppingProductDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingProductDetail"];
    page.goodsId = _goodsArray[indexPath.row][@"mgooId"];
    [self.navigationController   pushViewController:page animated:YES];
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _forSaleTableView) {
        return 77*VerticalRatio();
    }else{
    return 46*VerticalRatio();
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _forSaleTableView) {
        return _couponArray.count;
    }else{
    return self.storeClassifyArrary.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _forSaleTableView) {
        ForSalePaperTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellWithIdentifier];
        if (cell == nil) {
            cell= [[ForSalePaperTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellWithIdentifier];
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        NSDictionary * dic= _couponArray[indexPath.row];
        cell.forSaleMoney.text = [NSString stringWithFormat:@"%@元",dic[@"mscoDecreaseAmount"]];
        cell.forSaleInfo.text =[NSString stringWithFormat:@"订单满%@.00元使用", dic[@"mscoFullAmount"]];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[dic[@"mscoefficacyDate"] integerValue]/1000];
        NSDate *confromTimesp1 = [NSDate dateWithTimeIntervalSince1970:[dic[@"mscoInvalidateDate"] integerValue]/1000];
        [formatter setDateFormat:@"yyyy.MM.dd"];
        NSString *beginTime = [formatter stringFromDate:confromTimesp];
        NSString *endTime = [formatter stringFromDate:confromTimesp1];
        cell.forSaleDate.text = [NSString stringWithFormat:@"使用期限 %@ - %@",beginTime,endTime];
        //判断是否可以领取
        [cell.getButton setTitle:@"领取" forState:UIControlStateNormal];
        cell.getButton.layer.borderColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000].CGColor;
        [cell.getButton setTitleColor:[UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000] forState:UIControlStateNormal];
        cell.getButton.userInteractionEnabled = YES;
        NSString *isavailable = [NSString stringWithFormat:@"%@",dic[@"isavailable"]];
        if ([isavailable isEqualToString:@"0"]) {
            cell.getPaperBlock = ^(NSString * str){
                if ([str isEqualToString:@"1"]) {
                    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
                    [dic setObject:_couponArray[indexPath.row][@"mscoId"] forKey:@"counponId"];
                    self.shareApi.delegate=self;
                    [self.shareApi  requestOperationWithDic:dic withPath:SX_saveUserConpon withHttpType:@"POST" withTag:SX_SX_saveUserConpon];
                }
            };
        }else {
            [cell.getButton setTitle:@"已领取" forState:UIControlStateNormal];
            cell.getButton.layer.borderColor = [UIColor grayColor].CGColor;
            [cell.getButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            cell.getButton.userInteractionEnabled = NO;
        }
        
        return cell;
    }else{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 45, 190, 1), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.898 alpha:1.000];
    [cell addSubview:line];
    UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(17, 0, 150, 46), NO)];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor colorWithWhite:0.153 alpha:1.000];
    label.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
    label.text = self.storeClassifyArrary[indexPath.row][@"mgcaName"];
    [cell addSubview:label];
    return cell;
    }
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _forSaleTableView) {
        
    }else{
    self.mgooStoreTypeId = self.storeClassifyArrary[indexPath.row][@"mgcaId"];
    [UIView animateWithDuration:0.4 animations:^{
        _typeTableView.frame = flexibleFrame(CGRectMake(320, 0, 190, 568), NO);
        _openTypeButton.alpha = 0;
    } completion:^(BOOL finished) {
        _openTypeButton.hidden=YES;
        
    }];
    self.rightSwipeGesture.enabled = YES;
    [self getGoodsList];
    }
}
#pragma   mark---- textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self getGoodsList];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    return YES;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _listCollectionView || scrollView== _backScroView) {
        _offSet = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _listCollectionView || scrollView == _backScroView ) {
        if (scrollView.contentOffset.y>_offSet) {
            
            [_backScroView setContentOffset:CGPointMake(0, CGRectGetMinY(_typeButtonView.frame)) animated:YES];
            _backScroView.scrollEnabled = NO;
            _listCollectionView.scrollEnabled = YES;
        }else{
            if (scrollView == _backScroView) {
                [_backScroView setContentOffset:CGPointMake(0, 0) animated:YES];
                _backScroView.scrollEnabled = YES;
                _listCollectionView.scrollEnabled = NO;
            }else{
            if (decelerate == YES) {
               [_backScroView setContentOffset:CGPointMake(0, 0) animated:YES];
                _backScroView.scrollEnabled = YES;
                _listCollectionView.scrollEnabled = NO;
            }
        }
            
        }
    }
}


#pragma mark == 手势事件
-(void)action_swipeGesture:(UISwipeGestureRecognizer *)gesture{
    if (gesture == self.rightGesture) {
        [UIView animateWithDuration:0.4 animations:^{
            _typeTableView.frame = flexibleFrame(CGRectMake(320, 0, 190, 568), NO);
            _openTypeButton.alpha = 0;
        } completion:^(BOOL finished) {
            _openTypeButton.hidden=YES;
            
        }];
        self.rightSwipeGesture.enabled = YES;
        self.rightGesture.enabled = NO;
    }
    
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_backScroView.header endRefreshing];
    [_listCollectionView.footer endRefreshing];
    
    if (tag==SX_SX_queryStoreBanner) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [self.imageArray removeAllObjects];
            
            for (NSDictionary *data in database[@"result"]) {
                [self.imageArray addObject:data[@"sysImage"][@"simaImagUri"]];
            }
            _bannerScrollView.imageUrls = _imageArray;
            _bannerScrollView.delegate = self;
        }
        
    }else if (tag==SX_GetGoodsList) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.listCollectionView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.listCollectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.goodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.goodsArray addObject:entity];
                }
                _listCollectionView.dataSource = self;
                _listCollectionView.delegate = self;
                [_listCollectionView reloadData];
                
            });
        }
    }else if (tag == SX_AddGoodsCollectInfoTag){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }
    }else if (tag == SX_SX_queryStoreIsCollect){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSString * status = database[@"result"];
            if ([status isEqualToString:@"1"]) {
                _collectButton.selected = YES;
                _collectTitle.selected = YES;
            }else{
                _collectButton.selected = NO;
                _collectTitle.selected = NO;
            }
        }
        
    }else if (tag == SX_SX_queryMallStoreDetailInfo){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            self.storePhone = database[@"result"][@"mstoPhone"];
            
        }
    }else if (tag == SX_SX_queryMallStoreCategoryInfo){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            _typesArray = database[@"result"];
        }
    }else if (tag==SX_queryMallStoreCategoryInfoTag){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
           self.storeClassifyArrary  = database[@"result"];
            [_typeTableView reloadData];
        }
    }else if (tag == SX_SX_queryDesc){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSArray * array = database[@"result"];
            if (array.count>0) {
                NSDictionary * dic = array[0];
                _couponArray = [array mutableCopy];
                _forSaleTableView.dataSource = self;
                _forSaleTableView.delegate = self;
                [_forSaleTableView reloadData];
                
                 _forSaleLabel.text = [NSString stringWithFormat:@"满%@减%@",dic[@"mscoFullAmount"],dic[@"mscoDecreaseAmount"]];
                CGSize size = [_forSaleLabel.text sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                _forSaleImage.frame = CGRectMake(_forSaleLabel.frame.origin.x+size.width, _forSaleImage.frame.origin.y, _forSaleImage.frame.size.width, _forSaleImage.frame.size.height);
            }else{
                _scroView.frame = CGRectMake(0, 0, 320*VerticalRatio(), CGRectGetHeight(_scroView.frame)-38*VerticalRatio());
                _forSaleImage.hidden = YES;
                _forSaleLabel.hidden = YES;
                _forSaleButton.hidden = YES;
                _getForSaleButton.hidden = YES;
                
                _cutDownButton.frame = CGRectMake(_cutDownButton.frame.origin.x, _cutDownButton.frame.origin.y-35*VerticalRatio(), _cutDownButton.frame.size.width, _cutDownButton.frame.size.height);
                _cutDownPrice.frame = CGRectMake(_cutDownPrice.frame.origin.x, _cutDownPrice.frame.origin.y-35*VerticalRatio(), _cutDownPrice.frame.size.width, _cutDownPrice.frame.size.height);
                _cutDownLine.frame = CGRectMake(_cutDownLine.frame.origin.x, _cutDownLine.frame.origin.y-38*VerticalRatio(), _cutDownLine.frame.size.width, _cutDownLine.frame.size.height);
                _typeButtonView.frame = CGRectMake(_typeButtonView.frame.origin.x, _typeButtonView.frame.origin.y-38*VerticalRatio(), _typeButtonView.frame.size.width, _typeButtonView.frame.size.height);
                _listCollectionView.frame = CGRectMake(_listCollectionView.frame.origin.x, _listCollectionView.frame.origin.y-38*VerticalRatio(), _listCollectionView.frame.size.width, _listCollectionView.frame.size.height);
                _backScroView.contentSize = CGSizeMake(320, CGRectGetMinY(_listCollectionView.frame)+CGRectGetHeight(_listCollectionView.frame));
                if (_cutDownPrice.hidden == YES) {
                    _cutDownLine.hidden = YES;
                }
            }
           
        }
    
    }else if (tag == SX_SX_saveUserConpon){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            [UIView animateWithDuration:0.4 animations:^{
                _typeTableView.frame = flexibleFrame(CGRectMake(320, 0, 190, 568), NO);
                _forSalePaperView.frame = flexibleFrame(CGRectMake(0, 568, 320, 343), YES);
                _openTypeButton.alpha = 0;
            } completion:^(BOOL finished) {
                _openTypeButton.hidden=YES;
                
            }];
            self.rightSwipeGesture.enabled = YES;
        }
    }else if (tag== SX_SX_queryStoreOffline){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            NSArray * array = database[@"result"];
            if (array.count==0) {
            _scroView.frame = CGRectMake(0, 0, 320*VerticalRatio(), CGRectGetHeight(_scroView.frame)-38*VerticalRatio());
            _cutDownPrice.hidden = YES;
            _cutDownButton.hidden = YES;
            _listCollectionView.frame = CGRectMake(_listCollectionView.frame.origin.x, _listCollectionView.frame.origin.y-35*VerticalRatio(), _listCollectionView.frame.size.width, _listCollectionView.frame.size.height);
            _backScroView.contentSize = CGSizeMake(320, CGRectGetMinY(_listCollectionView.frame)+CGRectGetHeight(_listCollectionView.frame));
            _typeButtonView.frame = CGRectMake(_typeButtonView.frame.origin.x, _typeButtonView.frame.origin.y-35*VerticalRatio(), _typeButtonView.frame.size.width, _typeButtonView.frame.size.height);
            _cutDownLine.frame = CGRectMake(_cutDownLine.frame.origin.x, _cutDownLine.frame.origin.y-35*VerticalRatio(), _cutDownLine.frame.size.width, _cutDownLine.frame.size.height);
                if (_forSaleImage.hidden == YES) {
                    _cutDownLine.hidden = YES;
                }
            }else{
                NSDictionary * dic = array[0];
                _cutDownPrice.text = [NSString stringWithFormat:@"%@",dic[@"msopContent"]];
            }
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (UISwipeGestureRecognizer *)rightGesture
{
    if (!_rightGesture) {
        _rightGesture = ({
            UISwipeGestureRecognizer * rightSwipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(action_swipeGesture:)];
            rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
            
            rightSwipeGesture;
        });
    }
    return _rightGesture;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
